package servlet;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.session.SqlSession;

import POJO.Product;
import POJO.User;
import util.MybatisSession;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String name = request.getParameter("name");
		String password = request.getParameter("password");
	
		User user = new User();
		user.setName(name);
		user.setPassword(password);		
		
		HttpSession sess = request.getSession();
		
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		SqlSession session = MybatisSession.openSession();
		String statement = "mapper.userMapper.getUserByNamePassword";
		User u = session.selectOne(statement,user);
		if(u == null) {
			String msg = URLEncoder.encode("账号或密码错误","UTF-8");
			this.getServletContext().setAttribute("msg", msg);
			response.sendRedirect(request.getContextPath() + "/login.jsp?msg=" + msg);
			
		}else {
			
			sess.setAttribute("name", name);
			int num = 0;
			sess.setAttribute("num", num);
			List<Product> p = new ArrayList<>();
			sess.setAttribute("car", p);
			response.sendRedirect(request.getContextPath() + "/index.jsp");
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		doGet(request, response);
	}

}
